﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Physis.Client.Controllers {

    public class ApplicationController : Controller { // PHISYS.CLIENT.ENTERPRISE PROJECT 

        #region Protected Properties

        protected Models.ApplicationModel applicationModel = new Models.ApplicationModel ();

        #endregion 


        #region Constructors

        public ApplicationController () {

            // RESERVED FOR FUTURE USE

            // NONE OF THE PROPRETIES ARE VALID AT CONSTRUCTION TIME, THIS HAPPENS AT INITIALIZE
          
            return;

        }

        #endregion 


        #region Overrides

        protected override void Initialize (System.Web.Routing.RequestContext requestContext) {

            base.Initialize (requestContext);


#if DEBUG

            // VALIDATE GENERAL PERMISSIONS AND AUTHENTICATION 

            System.Diagnostics.Debug.WriteLine ("ApplicationController: " + Request.Url);

#endif


            if (applicationModel.Application.Session == null) {

                // USER NOT AUTHENTICATED OR NO SESSION AVAILABLE 

                // TRY TO AUTOMATICALLY AUTHENTICATE USING WINDOWS INTEGRATED IF NOT REQUESTING THE LOGIN PAGE 

                String routeController = (RouteData.Values.ContainsKey ("controller")) ? RouteData.Values["controller"].ToString().ToLower() : String.Empty;

                if ((routeController != "login") && (routeController != "permissiondenied")) {

                    // TRYING TO CONNECT TO APPLICATION AT NON-LOGIN CONTROLLER

                    // TRY WINDOW INTEGRATED AUTHENTICATION FROM HOSTED SERVICE 

                    Security.AuthenticationResponse authenticationResponse = applicationModel.Application.Authenticate (0); // ENTERPRISE ONLY AUTHENTICATION

                    if ((!authenticationResponse.IsAuthenticated) || (applicationModel.Application.Session.EnterprisePermissions.Count == 0)) {

                        Response.Redirect ("~/PermissionDenied", true);

                    }
                    
                }

                else {

                    // ALLOW THE UNAUTHENTICATED TO PASS THROUGH TO THE LOGIN CONTROLLER 

                    // THIS IS RESERVED FOR FUTURE USE TO SUPPORT NON-WINDOWS HOSTS

                }

            }

            // VALIDATE PERMISSIONS HERE

            return;

        }

        #endregion 

    }

}
